package com.stone.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.stone.domain.Student;
import com.stone.mapper.StudentMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
public class HelloController {

    @Resource
    private StudentMapper studentMapper;


    @ResponseBody
    @GetMapping("/test2")
    public List<Student> test2(HttpServletResponse response) {
        ExcelWriter excelWriter = null;
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            excelWriter = EasyExcelFactory.write(outputStream, Student.class).build();
            int j = (int) Math.ceil(0 / 3) + 1;
            for (int k = 1; k < j; k++) {
                List<Student> students = studentMapper.getList((k - 1) * 3, 3);
                WriteSheet writeSheet = EasyExcel.writerSheet(k, "设备列表" + k).build();
                excelWriter.write(students, writeSheet);
                students = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        excelWriter.finish();
        return null;
    }


    @ResponseBody
    @RequestMapping("/hello")
    public String hello() {
        return "Hello World";
    }

    private static volatile boolean initFlag = true;

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            System.err.println("第 " + i + " 次. ");
            test();
        }
    }

    public static void test() throws InterruptedException {
        new Thread(() -> {
            // System.err.println("waiting data .... ");
            while (initFlag) {
            }
            System.err.println("================= success ");
        }).start();

        new Thread(() -> {
            prepareData();
        }).start();

    }

    public static void prepareData() {
        // System.err.println("prepare data ..... ");
        initFlag = false;
        // System.err.println("prepare data end .....");
    }


    public void test1() {
        try {

        } catch (Exception e) {

        }
    }
}
